<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { tankChart } from '@/api/plan/plan'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      tankData: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');

      // 获取数据
      tankChart().then(response => {
        this.tankData = response.data;

        // 处理返回的数据，构建图表需要的格式
        const chartData = this.tankData.map(item => ({
          name: item.name, // 假设你的数据项有 name 属性
          value: item.value // 假设你的数据项有 value 属性
        }));

        // 设置图表的选项
        this.chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            left: 'center',
            bottom: '10',
            data: chartData.map(item => item.name) // 提取名称用于图例
          },
          series: [
            {
              name: 'WEEKLY WRITE ARTICLES',
              type: 'pie',
              roseType: 'radius',
              radius: [15, 95],
              center: ['50%', '38%'],
              data: chartData, // 使用处理后的数据
              animationEasing: 'cubicInOut',
              animationDuration: 2600
            }
          ]
        });
      }).catch(error => {
        console.error('获取数据失败:', error);
      });
    }
  }

}
</script>
